package com.yitiao.socket.chatroom.aio;

import com.yitiao.socket.chatroom.CommonConst;
import com.yitiao.socket.chatroom.demo.AcceptHandler;
import com.yitiao.socket.chatroom.demo.ClientHandler;
import lombok.Data;
import lombok.SneakyThrows;

import java.io.BufferedWriter;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Data
public class AioChatServer {

    private AsynchronousServerSocketChannel serverChannel;
    private AsynchronousChannelGroup asynchronousChannelGroup;
    // 实现广播
    private List<ClientChatHandler> connectedClients = new ArrayList<>();


    @SneakyThrows
    public void start() {
        //自定义ChannelGroup
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        asynchronousChannelGroup = AsynchronousChannelGroup.withThreadPool(executorService);
        serverChannel = AsynchronousServerSocketChannel.open();
        serverChannel.bind(new InetSocketAddress(CommonConst.HOST, CommonConst.PORT));
        System.out.println(serverChannel.getLocalAddress());
        while (true) {
            serverChannel.accept(null, new AcceptChatHandler(this));
            System.in.read();
        }

    }

    public static void main(String[] args) {
        AioChatServer server = new AioChatServer();
        server.start();
    }

    @SneakyThrows
    public void addClient(ClientChatHandler clientHandler) {
        connectedClients.add(clientHandler);
        System.out.println(clientHandler.getClientChannel().getRemoteAddress() + " join the chat");
    }

    @SneakyThrows
    public void removeClient(ClientChatHandler clientChatHandler) {
        connectedClients.remove(clientChatHandler);
        clientChatHandler.getClientChannel().close();
    }

    public String receive(ByteBuffer buffer) {
        return String.valueOf(StandardCharsets.UTF_8.decode(buffer));
    }

    public void forwardMsg(AsynchronousSocketChannel clientChannel, String fwdMsg) {
        for (ClientChatHandler connectedHandler : connectedClients) {
            AsynchronousSocketChannel client = connectedHandler.getClientChannel();
            if (!client.equals(clientChannel)) {
                //注意这个try，catch是自己加的
                try {
                    //将消息存入缓存区中
                    ByteBuffer buffer = StandardCharsets.UTF_8.encode(client.getRemoteAddress() + ":" + fwdMsg);
                    //写给每个客户端
                    client.write(buffer, null, connectedHandler);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
